﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using GrimorioApplication.Localization;
using System.Windows.Navigation;

using GrimorioApplication.Model;
using System.Windows.Media.Imaging;
using System.IO.IsolatedStorage;

namespace GrimorioApplication.Views
{
    public partial class ViewRecipeDetails : PhoneApplicationPage
    {
        // ID Della ricetta da caricare
        int idOfRecipe;

        public ViewRecipeDetails()
        {
            InitializeComponent();
            ApplicationBarInitializer();
        }

        // Come Su angerona, Leggo tutti i dati
        public void ReadAllData()
        {
            ReadIngredientsData();
            ReadRecipeData();
        }

        // Come angerona, leggo i dati della ricetta.
        public void ReadRecipeData()
        {
            DataRecipe recipeToRead = App.ViewModel.getRecipeWithSelectedId(idOfRecipe);

            // Colours
            label_receipeDescription.Foreground = (SolidColorBrush)Application.Current.Resources["PhoneAccentBrush"];
            label_recipeDish.Foreground = (SolidColorBrush)Application.Current.Resources["PhoneAccentBrush"];
            label_receipeDifficulty.Foreground = (SolidColorBrush)Application.Current.Resources["PhoneAccentBrush"];
            label_receipeMatchings.Foreground = (SolidColorBrush)Application.Current.Resources["PhoneAccentBrush"];
            label_receipeTime.Foreground = (SolidColorBrush)Application.Current.Resources["PhoneAccentBrush"];
            
            // Begin loading elements
            numberOfPeopleContent.Text = recipeToRead.NumberOfPeople.ToString();
            ratingStars.Value = (double)recipeToRead.Rating;
            var visibilityLight = (Visibility)Application.Current.Resources["PhoneLightThemeVisibility"];

            if (visibilityLight == Visibility.Visible)
            {
                Uri invertedOminImage = new Uri("/Img/AppIcons/user_100_100_INV.png", UriKind.Relative);
                ImageSource invertedOminImageSource = new BitmapImage(invertedOminImage);
                Uri invertedColorImage = new Uri("/Img/AppIcons/vegetarianIco_100_100_INV.png", UriKind.Relative);
                ImageSource sourceOfImg = new BitmapImage(invertedColorImage);
                recipeVegetarian.Source = sourceOfImg;
                UserIconImage.Source = invertedOminImageSource;
            }
            if (recipeToRead.IsVegetarian)
            {
                recipeVegetarian.Visibility = Visibility.Visible;
            }
            label_recipeNameContent.Text = recipeToRead.RecipeName;
            recipeDescriptionContent.Text = recipeToRead.Description;
            recipeDishContent.Text = recipeToRead.Dish;
            recipeDifficultyContent.Text = recipeToRead.Difficulty;
            recipeMatchingsContent.Text = recipeToRead.Matchings;
            recipePreparation.Text = recipeToRead.Preparation;
            recipeTimeContent.Text = recipeToRead.TimeForPreparation;

            if (recipeToRead.Image != "")
            {
                // Ricostruisco l'immagine prelevando lo stream dall'isostore (Dicono sia più veloce che non l'usare i byte[])
                BitmapImage bi = new BitmapImage();
                using (IsolatedStorageFile myIsoStore = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    using (IsolatedStorageFileStream imageFileStream = myIsoStore.OpenFile("/RecipePhotos/" + recipeToRead.Image, System.IO.FileMode.Open, System.IO.FileAccess.Read))
                    {
                        bi.SetSource(imageFileStream);
                    }
                    recipePhoto.Source = bi;
                }
            }
        }

        // Tricky: Ho creato due classi identiche su due namespace diversi. Appena posso sistemo e ne faccio solo una.
        // Il senso è avere una lista composta sia dagli ingredienti che dalla loro quantità, creando quindi un oggetto
        // avente le due proprietà e potendolo listare per i listBox.
        //
        public void ReadIngredientsData()
        {
            List<GrimorioApplication.ViewModel.IngredientsAndQuantity> ingredientsAndQuantity = App.ViewModel.getIngredientsAndQuantityOfRecipeSelected(idOfRecipe);
            IgredientsList.ItemsSource = ingredientsAndQuantity;
        }

        private void ApplicationBarInitializer()
        {
            ApplicationBar = new ApplicationBar();
            ApplicationBar.Mode = ApplicationBarMode.Default;
            ApplicationBar.Opacity = 1.0;
            ApplicationBar.IsVisible = true;
            ApplicationBar.IsMenuEnabled = false;

            // edit button
            ApplicationBarIconButton btn_edit = new ApplicationBarIconButton();
            btn_edit.IconUri = new Uri("/Img/appbar_edit.png", UriKind.Relative);
            btn_edit.Text = GrimorioLang.edit;
            ApplicationBar.Buttons.Add(btn_edit);
            btn_edit.Click += new EventHandler(btn_edit_Click);

            // delete button
            ApplicationBarIconButton btn_delete = new ApplicationBarIconButton();
            btn_delete.IconUri = new Uri("/Img/appbar_delete.png", UriKind.Relative);
            btn_delete.Text = GrimorioLang.delete;
            ApplicationBar.Buttons.Add(btn_delete);
            btn_delete.Click += new EventHandler(btn_delete_Click);
        }

        private void btn_delete_Click(object sender, EventArgs e)
        {
            // Quando cancello una ricetta devo cancellare la ricetta e le ricorrenze di quell'id nella tabella centrale

            // Delete from central table
            foreach (RecipeIngredients recing in App.ViewModel.recipeIngredientsOfSelectedRecipe(idOfRecipe))
            {
                App.ViewModel.DeleteRecipeToIng(recing);
            }

            App.ViewModel.DeleteRecipe(App.ViewModel.getRecipeWithSelectedId(idOfRecipe));

            NavigationService.GoBack();
        }


        // DA IMPLEMENTARE L'EDIT
        private void btn_edit_Click(object sender, EventArgs e)
        {
                NavigationService.Navigate(new Uri("/Views/EditRecipe.xaml?" + "ID=" + idOfRecipe, UriKind.Relative));
        }

        // Il passaggio dell'id della ricetta avviene qua:
        // invece che far caricare l'id dal costruttore uso i link di NavigationService + parametro da cercare.
        // Una volta preso, carica tutto.
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            string ID;
            if (NavigationContext.QueryString.TryGetValue("ID", out ID))
                idOfRecipe = Convert.ToInt32(ID);
            ReadAllData();
            base.OnNavigatedTo(e);
        }
    }
}